<template>
	<video src="" id="video"
		:style="{ width: vwidth + 'px',height: vheight + 'px', display:showVideo}"
		playsinline
		webkit-playsinline
		autoplay = true
		muted = true
		loop = true
		controls = false
		show-center-play-btn = false 
		object-fit = fill
	></video> 
</template>

<script>
	
//import Upload from "@/utils/fileupload/upload.js";
import * as jquery from "@/static/collect_face/jquery2.3.js";
import faceFilter from "@/static/neuralNets/jeelizFaceFilter.module.js"; 
import JeelizCanvas2DHelper from "@/static/neuralNets/JeelizCanvas2DHelper.js";
// 引入uni.webview.1.5.2.js
import '@/static/js/uni.webview.1.5.4.js'
let VIDEOELEMENT = null;
var  CVD = null; // return of Canvas2DDisplay
	
export default {
	props:{
		vwidth:{
			type:Number,
			default:240
		},
		vheight:{
			type:Number,
			default:240
		},
		erreText:{
			type:String,
			default:''
		},
		running:{
			type:Boolean,
			default:false
		}
	},
	data(){
		return {
			_errorText:'点击同意按钮开始拍摄',
			imgUrl:'',
			pauseStatus:false,
			startCut:false,
			faceCoo:null,
			detectState:null,
			showVideo:'block',
			appendCss:false,
			bgImgClass:'home_wai',
			bgImgClass2:'home_nei',
			mediaStreamTrack:null,
			startVideoStatus:false,
			useCamera:'qian', //qian代表前置摄像头 hou代表后置摄像头
		}
	},
	watch:{
		_errorText(val,old){
			console.log(val)
			this.$emit('update:errorText',val);
		}
	},
	mounted() {
		console.log('CCCC..............')
		console.log('CCCC..............')
		console.log('CCCC..............')
		console.log('CCCC..............')
		console.log('CCCC..............')
		if(faceFilter && typeof faceFilter.toggle_pause == 'function')
		{
			faceFilter.destroy();
		}
		console.log('CCCC')
		var that = this;//a
		this.$nextTick(function(){
			//初始化的时候给追加上canvas用作载体
			if($('#jeeFaceFilterCanvas').html() == undefined)
			{
				$('#show-content').append('<canvas class="appendcanvas" width="'+that.vwidth+'" height="'+that.vheight+'" id="jeeFaceFilterCanvas"></canvas>');
			}
			if($('#jeeFaceFilterCanvas2').html() == undefined)
			{
				$('#show-content').append('<canvas class="appendcanvas appendcanvas2"  width="'+that.vwidth+'" height="'+that.vheight+'" id="jeeFaceFilterCanvas2"></canvas>');
			}
			if(that.appendCss == false)
			{
				console.log('what???')
				$('uni-page-body').append(`<style>
				#jeeFaceFilterCanvas{
					display:none;
				}
				#jeeFaceFilterCanvas2{
					display:none;
					border-radius:50%
				}
				.uni-video-bar{
					display:none !important; //去除底部菜单栏
				}
				.uni-video-cover{
					display:none !important; //去除中间播放按钮
				}
				video{
					transform: rotateY(180deg);
					-webkit-transform: rotateY(180deg);    /* Safari 和 Chrome */
					-moz-transform: rotateY(180deg);
					border-radius:50% !important;
				}
				.uni-video-container{border-radius:50% !important;}
				.uni-video-video{border-radius:50% !important;}
				</style>`);
				that.appendCss  = true;
			}
			//uniapp编译过后无法获取video的dom，此处追加id
			$('#video').find('video').prop('id','myVideo');
			//$('#refCanvas').find('canvas').prop('id','jeeFaceFilterCanvas');
			
			// if(that.isTest == true)
			// { 
			// 	//是否是测试环境 测试环境直接调用视频
			// 	that.openCamera = true;
			// 	that.main();
			// }else{

			//}
		})
	},
	unmounted() {
		this.closeVideo();
	},
	methods:{
		closeVideo(){
				try{
					//页面卸载的时候关闭视频播放
					if(this.mediaStreamTrack)
					{
						this.mediaStreamTrack.getTracks()[0].stop();
					}
				}catch{
					console.log('close mediaStreamTrack error')
				}
				try{
					const video = document.getElementsByClassName('uni-video-video')[0];
					video.srcObject = null;
				}catch{
					console.log('close video.srcObject error')
				}
				try{
					faceFilter.toggle_pause(true);
					faceFilter.destroy(); //销毁注册对象
				}catch{
					console.log('close faceFilter toggle_pause error')
				}
		},
		changeUserCamera(type){
			this.useCamera = type;
			if(type == 'hou')
			{
				$('uni-page-body').append(`<style>
				video{
					transform: rotateY(0deg);
					-webkit-transform: rotateY(0deg);    /* Safari 和 Chrome */
					-moz-transform: rotateY(0deg);
					border-radius:50% !important;
				}
				</style>`);
			}else{
				$('uni-page-body').append(`<style>
				video{
					transform: rotateY(180deg);
					-webkit-transform: rotateY(180deg);    /* Safari 和 Chrome */
					-moz-transform: rotateY(180deg);
					border-radius:50% !important;
				}
				</style>`);
			}
			this.playVideo();
		},
		setRunning(status){
			console.log('setRunning')
			console.log(status)
			this.uploadHeadImg = '';
			this.imgUrl = '';
			this.pauseStatus = status;
			
			$('#jeeFaceFilterCanvas2').hide();
			//console.log(status)
			//true 暂停  false 继续执行
			faceFilter.toggle_pause(status);
			
			this.$emit('status',status)
		},
		playVideo() {
			var that = this;
			that.uploadHeadImg = '';
			that.imgUrl = '';
			that.startVideoStatus = true;
			that.startCut = false;
			var thatUseCamera = that.useCamera;
			if( thatUseCamera == 'qian')
			{
				var facingMode = 'user';
			}else if(thatUseCamera == 'hou'){
				var facingMode = { exact: "environment" };
			}
			if(faceFilter && typeof faceFilter.toggle_pause == 'function')
			{
				faceFilter.destroy();
			}
			setTimeout(function(){
				that.getUserMedia(
					{
						//摄像头拍摄的区域
						video: {
							width: 500,
							height: 500,
							facingMode: facingMode,
						}, /* 前置优先 */
					},
					that.success,
					that.error
				);
			},100)
		},
		// 访问用户媒体设备
		getUserMedia(constrains, success, error) {
			//this.success('11111')
			if(navigator.mediaDevices.getUserMedia){
				navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);//最新标准API
			}else if(navigator.webkitGetUserMedia){
				navigator.webkitGetUserMedia(constrains).then(success).catch(error);//webkit内核浏览器
			}else if(navigator.mozGetUserMedia){
				navagator.mozGetUserMedia(constrains).then(success).catch(error);//Firefox浏览器
			}else if(navigator.getUserMedia){
				navigator.getUserMedia(constrains).then(success).catch(error);//旧版API
			}else{
				this._errorText = "你的浏览器不支持访问用户媒体设备";
			}
		},
		success(stream){
			var that = this;
			this.$emit('start')
			that.openCamera = true;
			that._errorText = '请把人脸放在圆圈内拍摄脸部';
			that.mediaStreamTrack = stream;
			const video = document.getElementsByClassName('uni-video-video')[0];
			try{
				video.srcObject = stream;
			}catch{
				this.URL = window.URL || window.webkitURL;
				video.src = this.URL.createObjectURL(stream);
			}
			// webkit内核浏览器
			//苹果手机的系统弹框会阻止js的线程的继续执行 手动0.1秒之后自动执行代码
			setTimeout(() => {
		    	try{
					video.play();
				}catch{
					that._errorText = '视频流播放失败';
				}
		        that.main();
		    }, 100);
			
		},
		error(e){
			var that = this;
			that.startVideoStatus = false;
			this.$emit('error')
			
			if(this.useCamera == 'hou')
			{
				that._errorText = "调用后置摄像头失败:"+(e.name?e.name:'')+(e.message?e.message:'');
			}else{
				that._errorText = "调用前置摄像头失败:"+(e.name?e.name:'')+(e.message?e.message:'');
			}
			
		},
		main(){ // entry point
			var that = this;
			VIDEOELEMENT = document.getElementById('myVideo');
			//that._errorText = '请将完整脸部对准屏幕中央';
			  if (VIDEOELEMENT['currentTime'] && VIDEOELEMENT['videoWidth'] && VIDEOELEMENT['videoHeight']){
					//console.log(VIDEOELEMENT)
					that.start();
			  } else {
				setTimeout(function(){
					that.main();
				}, 100);
				//VIDEOELEMENT['play']();
			  }
		},
		start(){ // launched when the video is loaded
		  
		  var that = this;
		  faceFilter.init({
			canvasId: 'jeeFaceFilterCanvas',
			videoSettings: {
			  videoElement: VIDEOELEMENT
			},
			rotate:-90,
			NNCPath: '../../../static/neuralNets/', // root of NN_DEFAULT.json file
			callbackReady: function(errCode, spec){
			  if (errCode){
				//
				that._errorText = '人脸初始化出错'+  errCode;
				that.startVideoStatus = false;
				console.log('AN ERROR HAPPENS. SORRY BRO :( . ERR =', errCode);
				return;
			  }
			  CVD = JeelizCanvas2DHelper(spec);
			  CVD.ctx.strokeStyle = 'yellow';
			  //that._errorText = '初始化成功';
			},
			// called at each render iteration (drawing loop):
			callbackTrack: function(detectState){
				//console.log(detectState.detected)
			  that.detectState = '';
			  that.faceCoo = ''; 
			  //console.log(detectState)
			  if (detectState.detected>0.9){
					
					that.detectState = detectState;
					that.showVideo = 'block'; 
					$('#jeeFaceFilterCanvas2').hide();
					var faceCoo = CVD.getCoordinates(detectState);
					that.faceCoo = faceCoo;
					CVD.ctx.clearRect(0,0,CVD.canvas.width, CVD.canvas.height);
					CVD.update_canvasTexture();
					CVD.draw();
					var check = that.checkTrue();
					if(check)
					{
						that._errorText = '请保持不动，即将拍照';
						if( that.startCut == false)
						{
							//console.log('start setTimeout')
							that.startCut = true;
							setTimeout(function(){
								//console.log('setTimeout')
								that.setRunning(true);
								that.cutPhoto();
							},1000)
						}
					}
					//that.setRunning(true)
			  }else{
				  that.showVideo = 'block';
				  $('#jeeFaceFilterCanvas2').hide();
				  //that.$api.loadingMsg('请将人脸放置框中')
				  that._errorText = '请将完整脸部对准屏幕中央';
			  }
			  
			}
		  }); //end JEELIZFACEFILTER.init call
		},
		checkTrue(dump){
			//return true;
			var that = this;
			var faceCoo = that.faceCoo;
			var faceCooStr = JSON.stringify(faceCoo);
			var detectState  = that.detectState;
			if(!faceCoo || !detectState || detectState == '' || faceCoo == '')
			{
				return false;
			}
			var x = parseFloat(faceCoo.x).toFixed(2);
			var y = parseFloat(faceCoo.y).toFixed(2);
			var w = parseFloat(faceCoo.w).toFixed(2);
			var h = parseFloat(faceCoo.h).toFixed(2);
			var cw = parseFloat(CVD.canvas.width).toFixed(2);
			var ch = parseFloat(CVD.canvas.height).toFixed(2);
			var xcw = x/cw;
			var ycw = y/ch;
			if(xcw < 0.25 || xcw  > 0.5 || ycw > 0.45 || ycw < 0.1)
			{
				that._errorText = '请将完整脸部对准屏幕中央';
			}else{
				that._errorText = '';
			}
			if(that._errorText && that._errorText != '')
			{
				return false;
			}
			var faceMj = w * h  ;
			var allMj = cw * ch;
			var zhanbi = faceMj / allMj;
			var mianjiObj = {
				faceMj:faceMj,
				zhanbi:zhanbi
			}
			var mianjiobj2 = {
				cw:cw,
				ch:ch,
				allMj:allMj,
			}
			var mianjiStr = JSON.stringify(mianjiObj);
			var mianjiStr2 = JSON.stringify(mianjiobj2);
			if(zhanbi < 0.18)
			{
				that._errorText = '请离脸部近一点'
			}else if(zhanbi > 0.28 )
			{
				that._errorText = '请离脸部远一点'
			}else{
				return true;
			} 
			return false;
		},
		cutPhoto(rectparams){
			var that = this;
			var check = that.checkTrue(true);
			if(check == false)
			{
				that.setRunning(false);
				return ;
			}
			that._errorText = '拍照成功';
			
			this.$emit('success');
			
			that.showVideo = 'none';
			//$('#jeeFaceFilterCanvas').hide();
			$('#jeeFaceFilterCanvas2').show();
			CVD.ctx.clearRect(0,0,CVD.canvas.width, CVD.canvas.height);
			CVD.draw();
			/* console.log('oldrect',JSON.stringify(rectparams))
			var rectnew = this.opeRect(rectparams,'canvas',0.5);
			console.log('cutPhoto',JSON.stringify(rectnew)) */
			var clip = $('#jeeFaceFilterCanvas2')[0];
			var context_clip = clip.getContext('2d');
			/* var maxwidth = clip.width;
			var ratio = parseFloat(maxwidth/this.vwidth).toFixed(3);
			console.log(maxwidth,this.vwidth,ratio)
			var rect = this.opeRect(rect,'clipImage',ratio);
			console.log(rect); */
			context_clip.drawImage(
				$('#jeeFaceFilterCanvas')[0], //规定要使用的图像、画布或视频。
				0,0, //开始剪切的 x 坐标位置。
				CVD.canvas.width, CVD.canvas.height,  //被剪切图像的高度。
				0, 0,//在画布上放置图像的 x 、y坐标位置。
				this.vwidth,this.vwidth  //要使用的图像的宽度、高度
			);
			//context_clip.clearRect(0, 0, CVD.canvas.width, CVD.canvas.height);//清除画布
			//位移来做镜像翻转
			if(that.useCamera == 'qian')
			{
				//使用前置摄像头需要反转镜头
				context_clip.translate(this.vwidth, 0);
				context_clip.scale(-1, 1); //左右镜像翻转
				//ctx.translate(0, 160 + posy * 2);
				//ctx.scale(1, -1); //上下镜像翻转
				context_clip.drawImage($('#jeeFaceFilterCanvas2')[0], 0, 0, this.vwidth, this.vwidth);
			}
			
			this.imgUrl = clip.toDataURL("image/jpeg"); 
			//this.uploadHeadImg
			this.useImg();
		},
		useImg(){
			this.imgSize();
		},
		imgSize(){
			if (this.imgUrl) {
			        	// 获取base64图片byte大小
	        	const equalIndex = this.imgUrl.indexOf("="); // 获取=号下标
	        	let size;
		        if (equalIndex > 0) {
		          const str = this.imgUrl.substring(0, equalIndex); // 去除=号
		          const strLength = str.length;
		          const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
		          size = Math.floor(fileLength / 1024); // 向下取整
		        } else {
		          const strLength = this.imgUrl.length;
		          const fileLength = strLength - (strLength / 8) * 2;
		          size = Math.floor(fileLength / 1024); // 向下取整
		        }
		        if (size >= 200) {
		          	// 图片超过200k 重新再次压缩
					this.imgUrl =  $('#jeeFaceFilterCanvas2')[0].toDataURL("image/jpeg", 0.8);
					this.imgSize();
		        }else{
					this.$emit('image',this.imgUrl)
				}
	      	}
		}
	}
}
</script>

<style>
	
</style>